'''
Created on May 25, 2012

@author: thomas_dao
'''

from web import base
from web.base import BaseHandler
from web import urls
from entity.entity import Comment, Post, Photo
from web import util
from google.appengine.ext import ndb
from webapp2_extras.appengine.auth.models import User
import json
import logging
from app.query import comment_async

class CreateHandler(BaseHandler):
    @base.user_required
    def post(self):
        """
        @param comment: content, e.g: "this is a comment"
        @param comment_to: type, e.g: post, photo
        @param commentable_id: id of post or photo, e.g: 15
        @param with_tags: array of users tagged e.g: [1, 3, 4] 
        }
        """
        comment = Comment()
        comment.author = util.get_current_user_key()
        comment.comment = self.request.params.get('comment')
        
        # Get people tagged inside a comment
        with_tags = json.loads(self.request.params.get('with_tags'))
        comment.with_tags = []
        if with_tags:
            for user_id in with_tags:
                comment.with_tags.append(ndb.Key(User, user_id))
        
        comment_to = self.request.params.get('comment_to')
        commentable_id = self.request.params.get('commentable_id')
        if comment_to == "post":
            comment.commentable = ndb.Key(Post, int(commentable_id))
        elif comment_to == "photo":
            comment.commentable = ndb.Key(Photo, int(commentable_id))
        
        comment.put()
        
        # Write response back
        self.response.write(json.dumps(util.ndb_to_dict(comment)))
    

class ReadHandler(BaseHandler):
    def get(self):
        pass    

class UpdateHandler(BaseHandler):
    def post(self):
        pass
    

class DeleteHandler(BaseHandler):
    def post(self):
        pass    
        

class PostCommentsHandler(BaseHandler):
    @ndb.synctasklet
    def get(self, commentable_id):
        commentable_key = ndb.Key(Post, int(commentable_id))
        logging.info(commentable_key)
        comments = yield comment_async.get_by_commentable(commentable_key)
        # Write response back
        self.response.write(json.dumps(util.ndb_to_list(comments)))


class PhotoCommentsHandler(BaseHandler):
    @ndb.synctasklet
    def get(self, commentable_id):
        commentable_key = ndb.Key(Photo, int(commentable_id))
        comments = yield comment_async.get_by_commentable(commentable_key)
        # Write response back
        self.response.write(json.dumps(util.ndb_to_list(comments)))

app = urls.app

def main():
    app.run()

if __name__ == '__main__':
    main()